package service

import (
	"errors"
	"fmt"

	"github.com/jiedan/student-web/server/model"
	"gorm.io/gorm"
)

// StudentService 学生服务
type StudentService struct {
	DB *gorm.DB
}

// NewStudentService 创建学生服务
func NewStudentService(db *gorm.DB) *StudentService {
	return &StudentService{DB: db}
}

// CreateStudent 创建学生记录
func (s *StudentService) CreateStudent(userID uint, class string) (*model.Student, error) {
	// 检查用户是否存在
	var user model.User
	result := s.DB.First(&user, userID)
	if result.Error != nil {
		return nil, errors.New("user not found")
	}

	// 检查用户角色是否为学生
	var role model.Role
	result = s.DB.First(&role, user.RoleID)
	if result.Error != nil || role.Name != "student" {
		return nil, errors.New("user is not a student")
	}

	// 生成学号
	studentID, err := s.generateStudentID()
	if err != nil {
		return nil, err
	}

	// 创建学生记录
	student := model.Student{
		UserID:    userID,
		StudentID: studentID,
		Class:     class,
	}

	result = s.DB.Create(&student)
	if result.Error != nil {
		return nil, result.Error
	}

	return &student, nil
}

// generateStudentID 生成学号
func (s *StudentService) generateStudentID() (string, error) {
	// 获取最后一个学生记录
	var lastStudent model.Student
	result := s.DB.Order("id desc").First(&lastStudent)

	// 如果没有学生记录，从S0001开始
	if result.Error != nil {
		if errors.Is(result.Error, gorm.ErrRecordNotFound) {
			return "S0001", nil
		}
		return "", result.Error
	}

	// 解析最后一个学号
	var lastID int
	_, err := fmt.Sscanf(lastStudent.StudentID, "S%d", &lastID)
	if err != nil {
		return "", err
	}

	// 生成新学号
	newID := lastID + 1
	return fmt.Sprintf("S%04d", newID), nil
}

// GetStudentByUserID 根据用户ID获取学生信息
func (s *StudentService) GetStudentByUserID(userID uint) (*model.Student, error) {
	var student model.Student
	result := s.DB.Where("user_id = ?", userID).Preload("User").First(&student)
	if result.Error != nil {
		return nil, result.Error
	}

	return &student, nil
}

// GetStudentByID 根据学生ID获取学生信息
func (s *StudentService) GetStudentByID(id uint) (*model.Student, error) {
	var student model.Student
	result := s.DB.Preload("User").First(&student, id)
	if result.Error != nil {
		return nil, result.Error
	}

	return &student, nil
}

// GetStudentTotalCredits 获取学生已选课程总学分
func (s *StudentService) GetStudentTotalCredits(studentID uint) (float64, error) {
	var totalCredits float64

	// 查询学生已选课程
	var selections []model.CourseSelection
	result := s.DB.Where("student_id = ? AND status = 'selected'", studentID).Find(&selections)
	if result.Error != nil {
		return 0, result.Error
	}

	// 如果没有选课记录，返回0
	if len(selections) == 0 {
		return 0, nil
	}

	// 获取课程ID列表
	var courseIDs []uint
	for _, selection := range selections {
		courseIDs = append(courseIDs, selection.CourseID)
	}

	// 查询课程信息
	var courses []model.Course
	result = s.DB.Where("id IN ?", courseIDs).Find(&courses)
	if result.Error != nil {
		return 0, result.Error
	}

	// 计算总学分
	for _, course := range courses {
		totalCredits += course.Credits
	}

	return totalCredits, nil
}